package com.example.administrator.testc.WebViewCacahe;/**
 * Created by Administrator on 2016/5/24 0024.
 */

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.StatFs;
import android.util.Log;
import android.webkit.WebView;
import android.widget.ImageView;

import com.example.administrator.testc.mApp;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;

import pri.zey.custom.tools.Tkit;

/**
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>类描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>属性描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>方法描述
 */
public class TloadCache {

    private final String doMain = "http://m.xincheping.com";
    public static final String cacheDirPath = mApp.getContext().getFilesDir().getAbsolutePath() + "/webviewCache";
    private final String TAG = "TloadCache";
    private String WHOLESALE_CONV = "jpg";
    private long mTimeDiff = 1024 * 1024 * 60;
    private int MB = 1024;
    private int FREE_SD_SPACE_NEEDED_TO_CACHE = 5 * MB;
    private int CACHE_SIZE = 5 * MB;



    /**
     * TODO 根据文件的最后修改时间进行排序 *
     */
    class FileLastModifSort implements Comparator<File>{
        public int compare(File arg0, File arg1) {
            if (arg0.lastModified() >arg1.lastModified()) {
                return 1;
            } else if (arg0.lastModified() == arg1.lastModified()) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    public webBean inNameList(String url){
        File dir = new File(cacheDirPath);
        File[] files = dir.listFiles();
        if (files == null) {
            return null;
        }
        String filename = "";
        for (int i = 0; i < files.length;i++) {
            File file = files[i];
            filename = file.getName();
//            if(!url.endsWith(".com/"))
            if(true)
                if(filename.contains(convertUrlToFileName(url))){
//                    Log.i("TAGSS", "filename : " + filename);
                    if(filename.endsWith("jpg")){
                        webBean bean = new webBean();
                        bean.setInputStream(getInputStream(file));
                        if(filename.contains("jpg"))
                            bean.setFileType("image/jpg");
                        return bean;
                    }
                }
            else if(filename.contains(convertUrlToFileNameArr(url)[0])){

                }
        }
        return null;
    }

    /**
     * 计算sdcard上的剩余空间
     * @return
     */
    private int freeSpaceOnSd() {
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory() .getPath());
        double sdFreeMB = ((double)stat.getAvailableBlocks() * (double) stat.getBlockSize()) / MB;
        return (int) sdFreeMB;
    }

    public boolean load(WebView mWebView, String url) {
        if(Tkit.isBlank(url)){
            Log.w(TAG, "url is null");
            return false;
        }
        //判断sdcard上的空间
        if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
            Log.w(TAG, "Low free space onsd, do not cache");
            return false;
        }
        String fileName = "";
        fileName = convertUrlToFileName(url);
        String dir = getDirectory(fileName);
        File rootFile = new File(dir);
        if(!rootFile.exists()){
            rootFile.mkdirs();
            return false;
        }
        Log.i(TAG, "filePath : " + dir +"/" + fileName);
        if(fileName.contains("jpg") && fileName.contains("png") && fileName.contains("gif")) {
            return saveBitmap(dir + "/" + fileName, url);
        }else {
            return saveFile(dir + "/" + fileName, url);
        }
    }

    public boolean saveFile(final String fileStr, final String url){
        Log.i("TAGSS", "saveFile : " + url);
        final File file = new File(fileStr);
        if(file.exists()){
            return true;
        }else {
            new MyHttpClient().setRemoteUrl(url).setiHttpStr(new MyHttpClient.IHttpStr() {
                @Override
                public void onResult(String jsonStr) {
                    try {
                        try {
                            PrintWriter pw = new PrintWriter(new FileOutputStream(file));
                            pw.print(jsonStr);
                            pw.close();
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        Log.i(TAG, "File saved tosd");
                    } catch (Exception e) {
                        Log.w(TAG,"FileNotFoundException");
                    }
                }
            }).start();
            return false;
        }
    }

    public boolean saveBitmap(String fileStr, String url){
        Log.i("TAGSS", "saveBitmap : " + url);
        final File file = new File(fileStr);
        if(file.exists()){
            return true;
        }else {
            new MyHttp(url, new MyHttp.iHttpStream() {
                @Override
                public void onSuccess(Bitmap bitmap) {
                    try {
                        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outStream);
                        outStream.flush();
                        outStream.close();
                        Log.i(TAG, "Image saved tosd");
                    } catch (FileNotFoundException e) {
                        Log.w(TAG,"FileNotFoundException");
                    } catch (IOException e) {
                        Log.w(TAG,"IOException");
                    }
                }
            });
            return false;
        }
    }

    public boolean saveBitmap(final String fileStr, String url, final ImageView view){
        Log.i("TAGSS", "saveBitmap : " + url);
        final File file = new File(fileStr);
        if(file.exists()){
            return true;
        }else {
            new MyHttp(url, new MyHttp.iHttpStream() {
                @Override
                public void onSuccess(Bitmap bitmap) {
                    try {
                        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outStream);
                        outStream.flush();
                        outStream.close();
                        final Bitmap bm = BitmapFactory.decodeFile(fileStr);
                        view.post(new Runnable() {
                            @Override
                            public void run() {
                                if(bm != null){
                                    view.setImageBitmap(bm);
                                }else{
                                    Log.e("TAGSS", "404********");
                                }
                            }
                        });
                        Log.i(TAG, "Image saved tosd");
                    } catch (FileNotFoundException e) {
                        Log.w(TAG,"FileNotFoundException");
                    } catch (IOException e) {
                        Log.w(TAG,"IOException");
                    }
                }
            });
            return false;
        }
    }

    public Bitmap getBmpToSd(String url){
        File file = new File(getDirectory("") + convertUrlToFileName(url));
        if(file.exists()) {
            return BitmapFactory.decodeFile(file.getPath());
        }
        return null;
    }

    public InputStream getInputStream(File file){
        if(file.getName().contains("jpg") || file.getName().contains("png")){
            Bitmap bm = BitmapFactory.decodeFile(file.getPath());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 60, baos);
            return new ByteArrayInputStream(baos.toByteArray());
        } else {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                return fileInputStream;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public String[] convertUrlToFileNameArr(String url){
        String[] urlArr = url.split("/");
        String endStr = urlArr[urlArr.length - 1];
        String[] fileArr= endStr.split("\\.");
        return fileArr;
    }

    public String convertUrlToFileName(String url){
        String[] urlArr = url.split("/");
        String fileName = urlArr[urlArr.length - 1];
        if(fileName.contains("?"))
            return fileName.split("\\?")[0];
        else
            return fileName;
    }

    public String getDirectory(String filename){
        return cacheDirPath;
    }

    /**
     * 修改文件的最后修改时间
     * @param dir
     * @param fileName
     */
    public void updateFileTime(String dir,String fileName) {
        File file = new File(dir, fileName);
        long newModifiedTime = System.currentTimeMillis();
        file.setLastModified(newModifiedTime);
    }

    /**
     * 计算存储目录下的文件大小，当文件总大小大于规定的CACHE_SIZE或者sdcard剩余空间小于FREE_SD_SPACE_NEEDED_TO_CACHE的规定
     * 那么删除40%最近没有被使用的文件
     * @param dirPath
     */
    public void removeCache(String dirPath) {
        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        if (files == null) {
            return;
        }
        int dirSize = 0;
        for (int i = 0; i < files.length;i++) {
            if(files[i].getName().contains(WHOLESALE_CONV)) {
                dirSize += files[i].length();
            }
        }
        if (dirSize > CACHE_SIZE * MB ||FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {
            int removeFactor = (int) ((0.4 *files.length) + 1);
            Arrays.sort(files, new FileLastModifSort());
            Log.i(TAG, "Clear some expiredcache files || dirSize : " + dirSize);
            for (int i = 0; i <removeFactor; i++) {
                if(files[i].getName().contains(WHOLESALE_CONV)) {
                    files[i].delete();
                }

            }

        }

    }
    /**
     * 删除过期文件
     * @param dirPath
     * @param filename
     */
    public void removeExpiredCache(String dirPath, String filename) {

        File file = new File(dirPath,filename);

        if (System.currentTimeMillis() - file.lastModified() > mTimeDiff) {

            Log.i(TAG, "Clear some expiredcache files ");

            file.delete();
        }
    }
}
